import requests


class SendMsgToFeiShu:

    def __init__(self):
        self.session = requests.session()

    """
    发送测试数据结果统计
    """
    def send_test_results_msg(self, webhook, desc, cases_total, cases_success_total, cases_fail_total, cases_error_total,
                              cases_skipped_total, cases_time_total, failed_cases_list, cases_report_address):
        elements = [
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": f"**📋 {desc}**"
                }
            },
            {
                "tag": "hr"
            },
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": (
                        f"🔢 **用例总数**：{cases_total}\n"
                        f"✅ **成功用例数**：{cases_success_total}\n"
                        f"💥 **失败用例数**：{cases_fail_total}\n" 
                        f"❌ **错误用例数**：{cases_error_total}\n"
                        f"⏭️ **跳过用例数**：{cases_skipped_total}\n"
                        f"⏱️ **运行耗时**：{cases_time_total} 秒"
                    )
                }
            }
        ]

        # 有失败用例时，添加失败用例列表
        if failed_cases_list and failed_cases_list != "无":
            # 拼接所有失败用例
            failed_cases_md = "\n".join([f"- {case}" for case in failed_cases_list])

            elements.append({
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": f"**❗失败用例列表：**\n{failed_cases_md}"
                }
            })

        # 添加查看报告按钮
        elements.append({
            "tag": "action",
            "actions": [
                {
                    "tag": "button",
                    "text": {
                        "tag": "plain_text",
                        "content": "📄 查看测试报告"
                    },
                    "type": "primary",
                    "url": cases_report_address
                }
            ]
        })

        # 创建卡片消息
        card_payload = {
            "msg_type": "interactive",
            "card": {
                "config": {
                    "wide_screen_mode": True
                },
                "header": {
                    "title": {
                        "tag": "plain_text",
                        "content": "自动化测试结果"
                    }
                },
                "elements": elements
            }
        }

        # 发送请求
        response = self.session.post(url=webhook, json=card_payload)
        print("正在发送飞书测试结果卡片消息, 结果如下:")
        print(response.json())

    """
    通知人员（@某人或@所有人）
    """
    def send_notifying_officer(self, webhook, notifying_officer="@all"):
        """
        :param webhook: 飞书群机器人 webhook 地址
        :param notifying_officer: 通知人员手机号列表 ["185xxxx", "@all"]
        :return:
        """
        mention_text = ""
        for officer in notifying_officer:
            if officer == "@all":
                mention_text += "<at user_id=\"all\">所有人</at> "
            else:
                mention_text += f"<at user_id=\"{officer}\">{officer}</at> "

        body = {
            "msg_type": "text",
            "content": {
                "text": f"{mention_text}\n请注意查看测试结果。"
            }
        }
        response = self.session.post(url=webhook, json=body)
        print("正在通知飞书人员, 结果如下:")
        print(response.json())
